from django.db.models import F
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

from communication.models import Post, User


# Create your views here.
@api_view(['POST'])
def thumb_up_view(request):
    if request.method == 'POST':
        try:
            post = Post.objects.get(id=request.data['post'])
            user = User.objects.get(username=request.data['user'])
        except Exception as e:
            return Response(data={'message': '信息有误'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            if user in post.thumbers.all():
                post.thumbers.remove(user)
                post.thumb_up_count = F('thumb_up_count') - 1
                post.save()
                return Response(data={'message': '取消点赞成功'}, status=status.HTTP_200_OK)
            else:
                post.thumbers.add(user)
                post.thumb_up_count = F('thumb_up_count') + 1
                post.save()
                return Response(data={'message': '点赞成功'}, status=status.HTTP_200_OK)
    else:
        return Response(data={'message': '请求方法不被允许'}, status=status.HTTP_405_METHOD_NOT_ALLOWED)
